<template>
  <div class="membership-orders-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" :inline="true">
        <el-form-item label="订单号">
          <el-input
            v-model="searchForm.orderNo"
            placeholder="请输入订单号"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="用户名">
          <el-input
            v-model="searchForm.username"
            placeholder="请输入用户名"
            clearable
            style="width: 150px"
          />
        </el-form-item>
        <el-form-item label="套餐类型">
          <el-select v-model="searchForm.planType" placeholder="请选择套餐类型" clearable style="width: 150px">
            <el-option label="月度会员" value="monthly" />
            <el-option label="季度会员" value="quarterly" />
            <el-option label="年度会员" value="yearly" />
            <el-option label="终身会员" value="lifetime" />
          </el-select>
        </el-form-item>
        <el-form-item label="支付方式">
          <el-select v-model="searchForm.paymentMethod" placeholder="请选择支付方式" clearable style="width: 120px">
            <el-option label="支付宝" value="alipay" />
            <el-option label="微信支付" value="wechat" />
            <el-option label="银行卡" value="bank" />
          </el-select>
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 120px">
            <el-option label="待支付" value="pending" />
            <el-option label="已支付" value="paid" />
            <el-option label="已取消" value="cancelled" />
            <el-option label="已退款" value="refunded" />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :icon="Search">搜索</el-button>
          <el-button @click="resetSearch" :icon="Refresh">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-icon" style="background: #409eff">
              <el-icon><Money /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-number">¥{{ stats.totalAmount }}</div>
              <div class="stats-label">总收入</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-icon" style="background: #67c23a">
              <el-icon><Check /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-number">{{ stats.paidOrders }}</div>
              <div class="stats-label">已支付订单</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-icon" style="background: #e6a23c">
              <el-icon><Clock /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-number">{{ stats.pendingOrders }}</div>
              <div class="stats-label">待支付订单</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-icon" style="background: #f56c6c">
              <el-icon><Close /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-number">{{ stats.cancelledOrders }}</div>
              <div class="stats-label">已取消订单</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 表格区域 -->
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
      >
        <el-table-column prop="orderNo" label="订单号" width="180" />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="planName" label="套餐名称" width="150" />
        <el-table-column prop="planType" label="套餐类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getTypeTagType(row.planType)">
              {{ getTypeText(row.planType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="amount" label="订单金额" width="120">
          <template #default="{ row }">
            <span style="color: #f56c6c; font-weight: bold">¥{{ row.amount }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="paymentMethod" label="支付方式" width="120">
          <template #default="{ row }">
            <el-tag :type="getPaymentTagType(row.paymentMethod)">
              {{ getPaymentText(row.paymentMethod) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="订单状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column prop="payTime" label="支付时间" width="180">
          <template #default="{ row }">
            {{ row.payTime || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleViewDetail(row)" :icon="View">
              详情
            </el-button>
            <el-button
              v-if="row.status === 'paid'"
              type="warning"
              size="small"
              @click="handleRefund(row)"
              :icon="RefreshLeft"
            >
              退款
            </el-button>
            <el-button
              v-if="row.status === 'pending'"
              type="danger"
              size="small"
              @click="handleCancel(row)"
              :icon="Close"
            >
              取消
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 订单详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="订单详情"
      width="800px"
    >
      <div v-if="orderDetail" class="order-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="订单号">{{ orderDetail.orderNo }}</el-descriptions-item>
          <el-descriptions-item label="订单状态">
            <el-tag :type="getStatusTagType(orderDetail.status)">
              {{ getStatusText(orderDetail.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="用户名">{{ orderDetail.username }}</el-descriptions-item>
          <el-descriptions-item label="用户邮箱">{{ orderDetail.userEmail }}</el-descriptions-item>
          <el-descriptions-item label="套餐名称">{{ orderDetail.planName }}</el-descriptions-item>
          <el-descriptions-item label="套餐类型">
            <el-tag :type="getTypeTagType(orderDetail.planType)">
              {{ getTypeText(orderDetail.planType) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="原价">¥{{ orderDetail.originalPrice }}</el-descriptions-item>
          <el-descriptions-item label="实付金额">
            <span style="color: #f56c6c; font-weight: bold">¥{{ orderDetail.amount }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="支付方式">
            <el-tag :type="getPaymentTagType(orderDetail.paymentMethod)">
              {{ getPaymentText(orderDetail.paymentMethod) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="支付流水号">{{ orderDetail.transactionId || '-' }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ orderDetail.createTime }}</el-descriptions-item>
          <el-descriptions-item label="支付时间">{{ orderDetail.payTime || '-' }}</el-descriptions-item>
          <el-descriptions-item label="会员开始时间">{{ orderDetail.memberStartTime || '-' }}</el-descriptions-item>
          <el-descriptions-item label="会员结束时间">{{ orderDetail.memberEndTime || '-' }}</el-descriptions-item>
        </el-descriptions>

        <div v-if="orderDetail.remark" style="margin-top: 20px">
          <h4>备注信息</h4>
          <p>{{ orderDetail.remark }}</p>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 退款对话框 -->
    <el-dialog
      v-model="refundDialogVisible"
      title="订单退款"
      width="500px"
    >
      <el-form
        ref="refundFormRef"
        :model="refundForm"
        :rules="refundRules"
        label-width="100px"
      >
        <el-form-item label="退款金额" prop="refundAmount">
          <el-input-number
            v-model="refundForm.refundAmount"
            :min="0"
            :max="refundForm.maxAmount"
            :precision="2"
            style="width: 100%"
          />
          <div style="color: #909399; font-size: 12px; margin-top: 5px">
            最大可退款金额：¥{{ refundForm.maxAmount }}
          </div>
        </el-form-item>
        <el-form-item label="退款原因" prop="refundReason">
          <el-input
            v-model="refundForm.refundReason"
            type="textarea"
            :rows="3"
            placeholder="请输入退款原因"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="refundDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleRefundSubmit" :loading="refundLoading">
            确认退款
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, View, RefreshLeft, Close, Money, Check, Clock } from '@element-plus/icons-vue'

// 响应式数据
const loading = ref(false)
const detailDialogVisible = ref(false)
const refundDialogVisible = ref(false)
const refundLoading = ref(false)

// 搜索表单
const searchForm = reactive({
  orderNo: '',
  username: '',
  planType: '',
  paymentMethod: '',
  status: '',
  dateRange: []
})

// 分页
const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

// 统计数据
const stats = reactive({
  totalAmount: '12,580.00',
  paidOrders: 156,
  pendingOrders: 23,
  cancelledOrders: 8
})

// 表格数据
const tableData = ref([])

// 订单详情
const orderDetail = ref(null)

// 退款表单
const refundForm = reactive({
  orderId: null,
  refundAmount: 0,
  maxAmount: 0,
  refundReason: ''
})

const refundFormRef = ref(null)

// 退款验证规则
const refundRules = {
  refundAmount: [
    { required: true, message: '请输入退款金额', trigger: 'blur' }
  ],
  refundReason: [
    { required: true, message: '请输入退款原因', trigger: 'blur' }
  ]
}

// 生命周期
onMounted(() => {
  loadData()
})

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    // 模拟API调用
    setTimeout(() => {
      tableData.value = [
        {
          id: 1,
          orderNo: 'ORD202401150001',
          username: 'zhangsan',
          userEmail: 'zhangsan@example.com',
          planName: '年度会员',
          planType: 'yearly',
          originalPrice: 1188.00,
          amount: 599.00,
          paymentMethod: 'alipay',
          status: 'paid',
          transactionId: 'ALI2024011500001',
          createTime: '2024-01-15 10:30:00',
          payTime: '2024-01-15 10:32:15',
          memberStartTime: '2024-01-15 10:32:15',
          memberEndTime: '2025-01-15 10:32:15',
          remark: '用户主动购买年度会员'
        },
        {
          id: 2,
          orderNo: 'ORD202401150002',
          username: 'lisi',
          userEmail: 'lisi@example.com',
          planName: '月度会员',
          planType: 'monthly',
          originalPrice: 99.00,
          amount: 79.00,
          paymentMethod: 'wechat',
          status: 'pending',
          transactionId: null,
          createTime: '2024-01-15 11:00:00',
          payTime: null,
          memberStartTime: null,
          memberEndTime: null,
          remark: null
        },
        {
          id: 3,
          orderNo: 'ORD202401150003',
          username: 'wangwu',
          userEmail: 'wangwu@example.com',
          planName: '季度会员',
          planType: 'quarterly',
          originalPrice: 297.00,
          amount: 199.00,
          paymentMethod: 'alipay',
          status: 'cancelled',
          transactionId: null,
          createTime: '2024-01-15 12:00:00',
          payTime: null,
          memberStartTime: null,
          memberEndTime: null,
          remark: '用户取消订单'
        },
        {
          id: 4,
          orderNo: 'ORD202401150004',
          username: 'zhaoliu',
          userEmail: 'zhaoliu@example.com',
          planName: '终身会员',
          planType: 'lifetime',
          originalPrice: 2999.00,
          amount: 1999.00,
          paymentMethod: 'wechat',
          status: 'refunded',
          transactionId: 'WX2024011500001',
          createTime: '2024-01-15 13:00:00',
          payTime: '2024-01-15 13:02:30',
          memberStartTime: '2024-01-15 13:02:30',
          memberEndTime: null,
          remark: '用户申请退款，已处理'
        }
      ]
      pagination.total = 4
      loading.value = false
    }, 500)
  } catch (error) {
    console.error('加载数据失败:', error)
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  loadData()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    if (key === 'dateRange') {
      searchForm[key] = []
    } else {
      searchForm[key] = ''
    }
  })
  handleSearch()
}

// 查看详情
const handleViewDetail = (row) => {
  orderDetail.value = { ...row }
  detailDialogVisible.value = true
}

// 退款
const handleRefund = (row) => {
  refundForm.orderId = row.id
  refundForm.refundAmount = row.amount
  refundForm.maxAmount = row.amount
  refundForm.refundReason = ''
  refundDialogVisible.value = true
}

// 取消订单
const handleCancel = (row) => {
  ElMessageBox.confirm(
    `确定要取消订单"${row.orderNo}"吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 模拟取消操作
    ElMessage.success('订单取消成功')
    loadData()
  })
}

// 提交退款
const handleRefundSubmit = () => {
  refundFormRef.value.validate((valid) => {
    if (valid) {
      refundLoading.value = true
      // 模拟退款操作
      setTimeout(() => {
        ElMessage.success('退款申请提交成功')
        refundDialogVisible.value = false
        refundLoading.value = false
        loadData()
      }, 1000)
    }
  })
}

// 分页大小变化
const handleSizeChange = (size) => {
  pagination.size = size
  loadData()
}

// 当前页变化
const handleCurrentChange = (page) => {
  pagination.page = page
  loadData()
}

// 获取类型标签类型
const getTypeTagType = (type) => {
  const typeMap = {
    monthly: '',
    quarterly: 'success',
    yearly: 'warning',
    lifetime: 'danger'
  }
  return typeMap[type] || ''
}

// 获取类型文本
const getTypeText = (type) => {
  const typeMap = {
    monthly: '月度会员',
    quarterly: '季度会员',
    yearly: '年度会员',
    lifetime: '终身会员'
  }
  return typeMap[type] || type
}

// 获取支付方式标签类型
const getPaymentTagType = (method) => {
  const methodMap = {
    alipay: 'primary',
    wechat: 'success',
    bank: 'warning'
  }
  return methodMap[method] || ''
}

// 获取支付方式文本
const getPaymentText = (method) => {
  const methodMap = {
    alipay: '支付宝',
    wechat: '微信支付',
    bank: '银行卡'
  }
  return methodMap[method] || method
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  const statusMap = {
    pending: 'warning',
    paid: 'success',
    cancelled: 'info',
    refunded: 'danger'
  }
  return statusMap[status] || ''
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    pending: '待支付',
    paid: '已支付',
    cancelled: '已取消',
    refunded: '已退款'
  }
  return statusMap[status] || status
}
</script>

<style scoped>
.membership-orders-container {
  padding: 20px;
}

.search-card,
.table-card {
  margin-bottom: 20px;
}

.stats-row {
  margin-bottom: 20px;
}

.stats-card {
  cursor: pointer;
  transition: all 0.3s;
}

.stats-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.stats-content {
  display: flex;
  align-items: center;
  padding: 10px;
}

.stats-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 24px;
  margin-right: 20px;
}

.stats-info {
  flex: 1;
}

.stats-number {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.stats-label {
  font-size: 14px;
  color: #909399;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.order-detail {
  padding: 10px 0;
}

.dialog-footer {
  text-align: right;
}
</style>